package com.nursinghome.management.service;

import com.nursinghome.management.model.Elderly;
import com.nursinghome.management.model.User;
import com.nursinghome.management.repository.ElderlyRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ElderlyService {

    private final ElderlyRepository elderlyRepository;

    public ElderlyService(ElderlyRepository elderlyRepository) {
        this.elderlyRepository = elderlyRepository;
    }

    public List<Elderly> getAllElderly() {
        return elderlyRepository.findAll();
    }

    public Elderly getElderlyById(Long id) {
        return elderlyRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + id));
    }

    public Elderly getElderlyByUser(User user) {
        return elderlyRepository.findByUser(user)
                .orElseThrow(() -> new RuntimeException("Elderly not found for user: " + user.getUsername()));
    }

    public Elderly createElderly(Elderly elderly) {
        return elderlyRepository.save(elderly);
    }

    public Elderly updateElderly(Elderly elderly) {
        Elderly existingElderly = elderlyRepository.findById(elderly.getId())
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + elderly.getId()));

        existingElderly.setDateOfBirth(elderly.getDateOfBirth());
        existingElderly.setGender(elderly.getGender());
        existingElderly.setBloodGroup(elderly.getBloodGroup());
        existingElderly.setContactNumber(elderly.getContactNumber());
        existingElderly.setEmergencyContact(elderly.getEmergencyContact());
        existingElderly.setEmergencyContactName(elderly.getEmergencyContactName());
        existingElderly.setEmergencyContactRelation(elderly.getEmergencyContactRelation());
        existingElderly.setMedicalHistory(elderly.getMedicalHistory());
        existingElderly.setAllergies(elderly.getAllergies());
        existingElderly.setAdmissionDate(elderly.getAdmissionDate());
        existingElderly.setRoomNumber(elderly.getRoomNumber());
        existingElderly.setCareLevel(elderly.getCareLevel());
        existingElderly.setDietaryRestrictions(elderly.getDietaryRestrictions());
        existingElderly.setSpecialNeeds(elderly.getSpecialNeeds());

        return elderlyRepository.save(existingElderly);
    }

    public void deleteElderly(Long id) {
        elderlyRepository.deleteById(id);
    }
}